import io.lettuce.core.RedisClient;
import io.lettuce.core.RedisURI;
import io.lettuce.core.TrackingArgs;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.api.sync.RedisCommands;
import io.lettuce.core.codec.StringCodec;
import io.lettuce.core.support.caching.CacheAccessor;
import io.lettuce.core.support.caching.CacheFrontend;
import io.lettuce.core.support.caching.ClientSideCaching;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class Redis6CacheDemo {


    public static void main(String[] args) throws InterruptedException {
        // <1> 创建单机连接的连接信息
//        RedisURI redisUri = RedisURI.builder()                    //
//                .withHost("redis-18465.c276.us-east-1-2.ec2.cloud.redislabs.com")
//                .withPort(18465)
//                .withPassword("FfksNXhIiT1Gz47oLrGSOASFBZIOB4CT")
//                .build();

        RedisURI redisUri = RedisURI.builder()                    //
                .withHost("192.168.133.217")
                .withPort(6380)
                .build();
        RedisClient redisClient = RedisClient.create(redisUri);

        StatefulRedisConnection<String, String> otherParty = redisClient.connect();
        RedisCommands<String, String> commands = otherParty.sync();

        StatefulRedisConnection<String, String> connection = redisClient.connect();
// <2> 创建缓存访问器
        Map<String, String> clientCache = new ConcurrentHashMap<>(); //map 自动保存所有操作key的 key=value
        CacheFrontend<String, String> frontend = ClientSideCaching.enable(CacheAccessor.forMap(clientCache), connection,
                TrackingArgs.Builder.enabled());

        //服务器key发生变化，回调监听器
        connection.addListener(msg->{
            List<Object> content = msg.getContent(StringCodec.UTF8::decodeKey);
            if(msg.getType().equals("invalidate")){
                List<String> keys = (List<String>) content.get(1);
                keys.forEach(key->{
                    System.out.println(key+"已被移除");
                    System.out.println(clientCache);
                });
            }
        });
// <3> 客户端正常写入测试数据 k1 v1
        String key = "k1";
        commands.set(key, "v1");
// <4> 循环读取
        while (true) {
            // <4.1> 缓存访问器中的值，查看是否和 Redis 服务端同步
            String cachedValue = frontend.get(key);
            System.out.println("当前 k1 的值为:--->" + cachedValue);
            Thread.sleep(3000);
        }

    }

}
